Functions are one of the fundamental building blocks in JavaScript. A function is a reusable block of code designed to perform a particular task.
A function declaration defines a function with the specified parameters.
function functionName(parameter) {
---code---
return value;
}
functionName(x); //function call
A function expression defines a function inside an expression, and can be anonymous.
const greet = function(name) {
return "Hello, " + name + "!";
};
console.log(greet("Bob")); // Outputs: Hello, Bob!
Arrow functions provide a shorter syntax for writing functions.
const greet = (name) => {
return "Hello, " + name + "!";
};
console.log(greet("Charlie")); // Outputs: Hello, Charlie!
Functions can take parameters and be called with arguments.
function add(a, b) {
return a + b;
}
//or
// const add = (a,b)=>(a+b)
console.log(add(2, 3)); // Outputs: 5
Default parameters allow named parameters to be initialized with default values if no value or undefined
is passed.
function greet(name = "Guest") {
return "Hello, " + name + "!";
}
console.log(greet()); // Outputs: Hello, Guest!
Rest parameters allow a function to accept an indefinite number of arguments as an array.
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // Outputs: 10
Anonymous functions are functions without a name, often used as arguments to other functions.
setTimeout(function() {
console.log("This is an anonymous function.");
}, 1000);
An IIFE is a function that runs as soon as it is defined.
(function() {
console.log("This is an IIFE.");
})();